﻿using System;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Reflection;
using System.Xml;

namespace PickGold.Data.Linq
{
	public class MappingTable : MetaTable
	{
		private XmlNode _Config;
		private TableAttribute _Table;
		private MetaSource _Source;
		private MappingModel _Model;
		private Type _Entity;
		private MappingType _Row;

		public MappingTable(MetaSource source, MappingModel model, Type entity)
		{
			var cs = entity.GetCustomAttributes(typeof(TableAttribute), true);
			if (cs != null && cs.Length > 0)
				this._Table = cs[0] as TableAttribute;
			this._Config = model.GetNode(entity);
			this._Source = source;
			this._Model = model;
			this._Entity = entity;
		}

		public override MethodInfo DeleteMethod
		{
			get
			{
				return null;
			}
		}

		public override MethodInfo UpdateMethod
		{
			get
			{
				return null;
			}
		}

		public override MethodInfo InsertMethod
		{
			get
			{
				return null;
			}
		}

		public override MetaModel Model
		{
			get
			{
				return this._Model;
			}
		}

		public override MetaType RowType
		{
			get
			{
				if (this._Row == null)
					this._Row = this._Model.GetModel(this._Entity);
				return this._Row;
			}
		}

		public override string TableName
		{
			get
			{
				if (this._Config == null)
				{
					if (this._Table == null || string.IsNullOrWhiteSpace(this._Table.Name))
						return this._Entity.Name;

					return this._Table.Name;
				}

				var a = this._Config.Attributes[MetaSource.Name];
				if (a == null)
				{
					if (this._Table == null || string.IsNullOrWhiteSpace(this._Table.Name))
						return this._Entity.Name;

					return this._Table.Name;
				}

				if (string.IsNullOrWhiteSpace(a.Value))
				{
					if (this._Table == null || string.IsNullOrWhiteSpace(this._Table.Name))
						return this._Entity.Name;

					return this._Table.Name;
				}

				return a.Value;
			}
		}
	}
}
